package dao;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateTableSource;
import entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.rowset.JdbcRowSet;
import java.util.Arrays;
import java.util.List;

/**
 * @author liujunjie
 * @create 2021-09-01 15:25
 */
@Repository
public class BookDaoImpl implements BookDao {

    //注入JdbcTemplate,实现对数据库的crud
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //修改
    @Override
    public void uodate(Book book) {
        String sql = "update book set username=?,ustatus=? where userid=?";
        Object[] args = {book.getUsername(), book.getUstatus(), book.getUserid()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    //删除
    @Override
    public void delete(String id) {
        String sql = "delete from book where userid=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    //返回对象
    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from book where userid=?";
        //第二个参数：RowMapper接口，BeanPropertyRowMapper为其实现类，完成数据的封装
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);

        return book;
    }

    //查询返回集合
    @Override
    public List<Book> findAllBook() {
        String sql = "select * from book";
        List<Book> booklist = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return booklist;
    }

    //批量添加
    @Override
    public void batchAddBook(List<Object[]> batchArgs) {
        String sql = "insert into book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }


    //查询数据条数
    @Override
    public int selectCount() {
        String sql = "select count(*) from book";
        Integer coun = jdbcTemplate.queryForObject(sql, Integer.class);
        return coun;
    }


    //添加数据
    @Override
    public void add(Book book) {
        //创建sql语句
        String sql = "insert into book values(?,?,?)";
        //调用方法实现
        Object[] args = {book.getUserid(), book.getUsername(), book.getUstatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);


    }
}
